package com.bdqn.easybuy1.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class JDBCUtils {

    /**
     * 全局唯一的数据源
     */
    private static DataSource dataSource = null;

    /**
     * 静态代码块
     */
    static {
        try {
            Properties pro = new Properties();
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            System.out.println("Druid数据源初始化失败");
        }
    }

    /**
     * 通过Druid数据源获取连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        if (dataSource != null) {
            return dataSource.getConnection();
        }
        return null;
    }
}
